<?php
/**
 * AJAX Handler for Tags: Delete - Delete a tag from a project
 * NOTE:    This does not delete a Tag that is setup in the database in `user_tags`. 
 *	    It merely deletes the link in `tool_tags` from the project to that tag.
 * 
 * I have made sure Libdebug is silent in AJAX. This is because it can intefere with the HTML/Javascript as Libdebug Appends after </html>.
 * If you have a problem and need to debug comment $_LIBDEBUG->silence(); (the framework must also be in debugging mode for this to work)
 */

    $_ECLIPSEMDE = array();
    
    // Disable Templating System
    $_ECLIPSEMDE['TEMPLATING'] = false;
    require_once('../../SiteIncludes.GLOBAL.php');
    
    // Tell libdebug to never print out error information - overrides debugging flags in fwork
    $_LIBDEBUG->silence();
    
    if(EclipseMDE::runningOnMod_Rewrite() === false) {
	// Security Guard, Do Not Let This be accessed by any other means than mod_rewrite
	header("HTTP/1.1 400 Bad Request");
	die($nok_caller);
    }
    
    // Ensure all variables needed are set
    if(isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER !== false && isset($gVAR['alias']) !== false && isset($gVAR['tagID']) !== false) {
	try {
	    $Project =& $ProjectStash->get($gVAR['alias']);
	    
	    if($Project->userCanEdit($_LOGGEDINUSER->get_userid()) === true) {
		
		$pid = $Project->getID();
		$tid = $sql_conx->real_escape_string(''.$gVAR['tagID']);
		$query = $sql_conx->query("DELETE FROM `tool_tags` WHERE `pid` = '{$pid}' AND `tid` = '{$tid}'");
		echo "DELETE FROM `tool_tags` WHERE `pid` = '{$pid}' AND `tid` = '{$tid}'";
		if($sql_conx->affected_rows === 0) {
		    header("HTTP/1.1 400 Bad Request");
		    die($nok_caller);
		} else {
		    header("HTTP/1.1 200 OK");
		    $Project->updateTriggered();
		    $Project->updateWrite($_LOGGEDINUSER->get_userid(), ($Project->isMaintainer($_LOGGEDINUSER->get_userid()) === true ? ProjectEditType::DelTag : ProjectEditType::AdminDelTag), array($tid));
		    die($ok_caller);
		}
	    } else {
		throw new InvalidProjectException('');
	    }
	    
	} catch(InvalidProjectException $e) {
	    header("HTTP/1.1 400 Bad Request");
	    die($nok_caller);
	}
    } else {
	header("HTTP/1.1 400 Bad Request");
	die($nok_caller);
    }
?>
